// When an item or a file is modified //
// trigger List: ContractList

/* --- trigger conditions ---

greater(triggerOutputs()['body/ID'], 100)
or(equals(triggerOutputs()['body/ApprovalResult'], 'Proceed'),equals(triggerOutputs()['body/ApprovalResult'], 'Conditional Go'))

--- trigger conditions --- */


// 表服务
var List_ContractList = {}
var List_ApprovalData = {}
var List_Approver = {}
var List_Department = {}
var List_OtherServicesDepartment = {}

// Main start 

// Update item 2
List_ContractList.update(id=triggerOutputs()['body/ID'],
{
    "item/InvolveMonetary": true,
    "item/LegalInvolved": true,
    "item/ApprovalResult": null,
    "item/ApprovalRemark": null
})


var node = triggerOutputs()['body/ApprovalNode']
var ID = triggerOutputs()['body/ID']
var Round = float(triggerOutputs()['body/ApprovalBatch'])

// 初始化变量-CFO Office Claims
var CFO_Office_Claims = []

// 初始化变量-CFO Office Email
var CFO_Office_Email = []


// Start ----- 获取CFO Office Claims -------

var Get_Items = List_Approver.getItems("Role eq 'CFO Office'")
var approvlal_Claims = Get_Items.select(x => x['Approver']['Claims'])
CFO_Office_Claims = approvlal_Claims

var approval_Emails = Get_Items.select(x => x['Approver']['Email'])
CFO_Office_Email = approval_Emails

// End ----- 获取CFO Office Claims -------



// 初始化变量-所有需审批的角色

var 所有需审批的角色 = []


// Start ----- 获取所有需要审批的角色 -----

// 获取合同列表项
var Get_item = List_ContractList.getItem(id=triggerOutputs()['body/ID'])

// 当前审批轮数的待审批节点
var Get_items_2 = List_ApprovalData.getItems(`ContractId eq '${Get_item['body/ID']}' and result eq null and batch_no eq ${float(Get_item['body/ApprovalBatch'])}`)

var ls_position = Get_items_2['body/value'].select(x=> x['Position'])
所有需审批的角色 = ls_position

// End   ----- 获取所有需要审批的角色 -----



// 初始化变量-当前角色
var 当前角色 = ''


// Start ----- 获取当前角色Position -----

var Get_item_2 = List_ContractList.getItem(triggerOutputs()['body/ID'])
var Get_items_3 = List_ApprovalData.getItems(`"ContractId eq '${Get_item_2['body/ID']}' and batch_no eq ${float(Get_item_2['body/ApprovalBatch'])} and ApprovalNode eq '${node}'"`)

var 筛选数组 = Get_items_3['body/value'].where(x => x['AllApprover'].contains(Get_item['body/ApprovalResultUser']))
当前角色 = 筛选数组[0].Position

// End   ----- 获取当前角色Position -----


var ApprovedUser = []
var SameGroup = []
var ApprovalUser = []

// 初始化变量-下一角色
var 下一角色 = ""

// 初始化变量-下一节点
var 下一节点 = ''


// ----- 根据角色执行对应流程，发送邮件 -----

// ----- 更新申请表和ApproveData -----

var Get_item_4 = List_ContractList.getItem(triggerOutputs()['body/ID'])

// 获取当前审批轮次所有未审核的 approve data 节点
var Get_items_6 = List_ApprovalData
    .getItems(`ContractId eq '${Get_item_4['body/ID']}'  and result eq null and batch_no eq ${float(Get_item_4['body/ApprovalBatch'])}`)
    .orderBy("ID asc")

// 查找未审核的节点中审批人包含当前审批人的节点的所有审批人
var 筛选数组_4 = Get_items_6['body/value'].where(x => x['AllApprover'].contains(Get_item['body/ApprovalResultUser']))
var 当前审批角色的AllApprover_2 = 筛选数组_4[0]['AllApprover']


// ----- 设置ApprovalUser 2
// 从 ApprovalUser 中排除掉当前 ApprovalData 审批节点中所有的审批人 AllApprover
var 筛选数组_5 = Get_item_4['body/ApprovalUser'].where(x => !当前审批角色的AllApprover_2.contains(x))
ApprovalUser = 筛选数组_5.select(x => x['Claims'])


// 如果是CEO Office
if(当前角色 == 'CEO Office')
{
    // 从 ApprovalUser 中仅排除当前审批人 ApprovalResultUser. CEO Office 角色中其他人都必须审批
    var 筛选数组_7 = Get_item_4['body/ApprovalUser'].where(x => !Get_item_4['body/ApprovalResultUser'].contains(x))
    var 选择_14 = 筛选数组_7.select(x => x['Claims'])
    ApprovalUser = 选择_14
}


// 设置ApprovedUser 2
var 编辑_4 = union(createArray(Get_item_2['body/ApprovalResultUser']), Get_item_4['body/ApprovedUser'])
var 选择_8 = 编辑_4.select(x => x['Claims'])
ApprovedUser = 选择_8

// Bug: 如果是 CEO Office 角色，可能不应该放入 SameGroup
// 设置SameGroup 2
var 编辑_5 = union(Get_item_4['body/SameGroup'], 当前审批角色的AllApprover_2)
var 选择_9 = 编辑_5.select(x => x['Claims'])
SameGroup = 选择_9

// Update item-申请表 3
var Update_item_申请表_3 = List_ContractList.update(id=triggerOutputs['Id'],
    {
      "item/InvolveMonetary": true,
      "item/LegalInvolved": true,
      "item/ApprovalUser": ApprovalUser,
      "item/ApprovedUser": ApprovedUser,
      "item/SameGroup": SameGroup
    }
)

// Update item 3
// 更新当前审批节点状态
var Update_item_3 = List_ApprovalData.update(id=筛选数组_4[0].ID,
    {
        "item/Title": null,
        "item/Approver/Claims": Get_item_4['body/ApprovalResultUser/Claims'],
        "item/is_completed": true,
        "item/result": triggerOutputs()['body/ApprovalResult'],
        "item/remark": triggerOutputs()['body/ApprovalRemark'],
        "item/CompletedDate": utcNow(),
        "item/is_validate": true,
        "item/is_revoked": false,
        "item/is_backup": false
    }
)


// 如果当前角色是others、Legal、CFO Office
var str = "IT; Security; Digital; rocurement; Logistic;"
if(str.contains(当前角色) 
    || "CFO Office" == 当前角色
    || "Legal" == 当前角色
)
{
    // 更新申请表以及ApproveData

    var Get_item_3 = List_ContractList.getItem(triggerOutputs()['body/ID'])
    var Get_items_4 = List_ApprovalData
        .getItems(`ContractId eq '${Get_item_3['body/ID']}' and ApprovalNode eq '${Get_item_3['body/ApprovalNode']}'   and result eq null and batch_no eq ${float(Get_item_3['body/ApprovalBatch'])}`)

    下一角色 = "Department Head"
    下一节点 = "DepartmentHead"

    // 第一阶段的角色都审批通过了，则进入下一审批阶段
    if(length(Get_items_4['body/value']) == 0)
    {
        var Get_items_5 = List_ApprovalData
            .getItems(`ContractId eq '${Get_item_3['body/ID']}' and batch_no eq ${float(Get_item_3['body/ApprovalBatch'])} and Position eq '${下一角色}'`)

        ApprovalUser = null
        
        Get_items_5.forEach(item => {
            var 选择_6 = item['AllApprover'].select(x=>x['Claims'])

            选择_6.forEach(item1 => {
                ApprovalUser.append(item1)
            })
        })

        // Update item-申请表 2
        List_ContractList.update(id=triggerOutputs()['body/ID'],
            {
                "item/InvolveMonetary": true,
                "item/LegalInvolved": true,
                "item/ApprovalUser": ApprovalUser,
                "item/ApprovalNode": 下一节点
            })

        // 发送电子邮件
        ApprovalUser.forEach(user => {
            SendEmailV2(user, 'message')
        })

    }

}


// 如果当前角色是Finance 
if("Finance".contains(当前角色))
{
    // 更新申请表以及ApproveData 2
    var Get_item_5 = List_ContractList.getItem(triggerOutputs()['body/ID'])

    var Get_items_8 = List_ApprovalData
    .getItems(`ContractId eq '${Get_item_5['body/ID']}' and ApprovalNode eq '${Get_item_5['body/ApprovalNode']}'   and result eq null and batch_no eq ${float(Get_item_5['body/ApprovalBatch'])}`)

    var 筛选数组_2 = Get_items_8['body/value'].where(x => contains(x['Position'], 'Finance '))

    if(length(筛选数组_2) == 0)
    {
        var Update_item_申请表 = List_ContractList.update(id=triggerOutputs()['body/ID'],
            {
                "item/InvolveMonetary": true,
                "item/LegalInvolved": true,
                "item/ApprovalNode": 下一节点 // Bug：下一节点值还没有设置
            })

        var 选择_3 = Get_item_5['body/ApprovalUser'].select(x => x['Claims'])
        var 编辑_2 = union(选择_3, CFO_Office_Claims) // Bug: CFO_Office_Claims 本身已包含 Approval 表中所有 CFO Office 了

        var Update_item_申请表_4 =  List_ContractList.update(id=triggerOutputs()['body/ID'],{
            "item/InvolveMonetary": true,
            "item/LegalInvolved": true,
            "item/ApprovalUser": 编辑_2
            })

        CFO_Office_Email.forEach(item=>{
            // Get user profile (V2) 2
            var profile = UserProfile_V2(item)
            SendEmailV2(profile)
        })
    }
}


// 如果当前角色是Department Head
if("Department Head" == 当前角色)
{
    // 更新申请表以及ApproveData 3

    if(所有需审批的角色.contains("Senior Department Head"))
    {
        下一角色 = "Senior Department Head"
        下一节点 = "SeniorDepartmentHead"
    }

    // Bug: 如果 下个所审批的角色不包含 Senior Department Head 那么下一节点应该是 CEO Office , 这里没有正确设置下一角色

    var Get_items_9 = List_ApprovalData.getItems(`ContractId eq '${ID}' and batch_no eq ${Round}  and Position eq '${下一角色}'`)

    ApprovalUser = null

    Get_items_9['body/value'].forEach(item => {
        var 选择_4 = item['AllApprover'].select(x => item['Claims'])
        
        选择_4.forEach(claims => {
            ApprovalUser.append(claims)
        })
    })

    var Update_item_申请表_5 = List_ContractList.update(id=triggerOutputs()['body/ID'], {
      "item/InvolveMonetary": true,
      "item/LegalInvolved": true,
      "item/ApprovalUser": ApprovalUser,
      "item/ApprovalNode": 下一节点
    })

    Update_item_申请表_5['body/ApprovalUser'].forEach(item => {
        SendEmailV2(item)
    })
}


// 如果当前角色是Senior Department Head
if("Senior Department Head" == 当前角色)
{
    // 更新申请表以及ApproveData 5

    下一角色="CEO Office"
    下一节点="CEOOffice"
    ApprovalUser=null

    var Get_items_11 = List_ApprovalData.getItems(`ContractId eq '${D}' and batch_no eq ${Round}  and Position eq '${下一角色}'`)
    Get_items_11['body/value'].forEach(item => {
        var 选择_10 = item['AllApprover'].select(x => x['Claims'])

        选择_10.forEach(claims => {
            ApprovalUser.append(claims)
        })
    })

    var Update_item_申请表_7 = List_ContractList.update(id=triggerOutputs()['body/ID'], {
        "item/InvolveMonetary": true,
        "item/LegalInvolved": true,
        "item/ApprovalUser": ApprovalUser,
        "item/ApprovalNode": 下一节点
    })

    Update_item_申请表_7['body/ApprovalUser'].forEach(item => {
        SendEmailV2(item)
    })
}


// 如果当前角色是CEO Office
if("CEO Office" == 当前角色)
{
    // 更新申请表以及ApproveData 4

    var Get_item_6 = List_ContractList.getItem(triggerOutputs()['body/ID'])
    var Get_items_7 = List_ApprovalData.getItems(`ContractId eq '${ID}'   and result eq null and batch_no eq ${Round}`)

    下一角色 = "CEO"
    下一节点 = "CEO"

    if(length(Get_items_7['body/value']) == 1)
    {
        var Get_items_10 = List_ApprovalData.getItems(`ContractId eq '${Get_item_6['body/ID']}' and batch_no eq ${float(Get_item_6['body/ApprovalBatch'])} and Position eq '${下一角色}'`)
        ApprovalUser=null

        Get_items_10['body/value'].forEach(item => {
            var 选择_5 = item['AllApprover'].select(x => x['Claims'])
            选择_5.forEach(claims => {
                ApprovalUser.append(claims)
            })
        })

        var Update_item_申请表_6 = List_ContractList.update(id=triggerOutputs()['body/ID'],{
            "item/InvolveMonetary": true,
            "item/LegalInvolved": true,
            "item/ApprovalUser": ApprovalUser,
            "item/ApprovalNode": 下一节点
        })

        Update_item_申请表_6['body/ApprovalUser'].forEach(item => {
            SendEmailV2(item)
        })

    }
}


// 如果当前角色是CEO
if("CEO" == 当前角色)
{
    var Update_item__更新项目的ApprovalUser_2 = List_ContractList.update(id=variables('ID'),{
      "item/InvolveMonetary": true,
      "item/LegalInvolved": true,
      "item/ApprovalUser": null,
      "item/FlowStatus": "Approved",
      "item/ApprovalNode": "ApplicantUpload"
    })
}
